﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using openlaunch;
using System.Threading;
using System.Runtime.InteropServices;
using System.Diagnostics;
using IWshRuntimeLibrary;

namespace OpenLauncher
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        /// 
        /// 
        [STAThread]
        static void Main(string[] args)
        {
            bool gui = true;
            bool shortcut = false;
            string pluginname = null;
            for(int i = 0; i<args.Length; i++)
            {
                //check the args for certain settings.
                switch (args[i])
                {
                    case "-nogui":
                        gui = false;
                        break;
                    case "-psexec":
                        pluginname = args[i+1];
                        pluginname = pluginname.Replace("%20", " ");
                        i++;
                        break;
                    case "-shortcut":
                        shortcut = true;
                        break;
                    
                }
            }
            if (pluginname == null)
            {
                if (gui == false)
                {
                    try
                    {
                        WriteHeader();
                        Console.WriteLine(@"------------------   Error   ------------------");
                        Console.WriteLine(@"Error: Missing argument '-psexec'              ");
                        Console.WriteLine(@"-----------------------------------------------");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }
                //Show err
            }
            if (gui == true)
            {
                //setConsoleWindowVisibility(false, Console.Title);
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
            else
            {
                if (shortcut == true)
                {
                    
                }
                //AllocConsole();
                //Load the plugins and execute the specified one.
                if (pluginname == null || pluginname.Length == 0)
                {
                }
                else
                {
                    try
                    {
                        string path = Application.StartupPath + @"/plugins/";
                        string[] f = Directory.GetFiles(path);
                        foreach (string g in f)
                        {
                            if (g.Contains(".olp"))
                            {
                                byte[] bytes = PluginProtector.DecryptData(System.IO.File.ReadAllBytes(g));
                                var assm = Assembly.Load(bytes);
                                foreach (Type tsype in assm.GetTypes())
                                {
                                    foreach (var tys in tsype.GetInterfaces())
                                    {
                                        if (tys.Name == "OpenPlugin")
                                        {
                                            try
                                            {
                                                OpenPlugin oplugin = (OpenPlugin)Activator.CreateInstance(tsype);
                                                if (oplugin.Name == pluginname)
                                                {
                                                    //Start the thread.
                                                    oplug = (OpenPlugin)oplugin; //Set the static plugin to run
                                                    Thread t = new Thread(new ThreadStart(RunThread)); //Run the plugin on a new thread
                                                    //oplugin.Run();
                                                    t.Start();
                                                    break;
                                                }
                                                else
                                                {
                                                    break;
                                                }
                                            }
                                            catch
                                            {
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch
                    {
                    }
                }
            }
        }
        static void SendToConsole(string v)
        {
            //MessageBox.Show("Writing to console");
            Console.WriteLine(v);
        }
        static OpenPlugin oplug = null;
        static void RunThread()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            oplug.ConsoleRun(); //Run the plugin
        }
        static void WriteHeader()
        {
            //Generate a random number
            Random f = new Random();
            //Get the number
            string m = System.IO.File.ReadAllText(Application.StartupPath + "//theme");
            //Decrypt our text
            DarthEncrypt gb = new DarthEncrypt();
            gb.PassPhrase = "KASOJLFALSDHJK#@@IUHFK!@KJH@!#KJHFAS";
            string gf = gb.DecryptString(m);
            string[] g = gf.Split('Q');
            int rand = f.Next(0, g.Length - 1);
            //Read our file that has designs in it.
            //Show the Dialog based on the number.
            Console.WriteLine(g[rand]);
        }
        public static void CreateShortcut(string path, string iconname, string title)
        {
            string rundllPath = path;
            // Create a new instance of WshShellClass
            WshShellClass WshShell = new WshShellClass();
            // Create the shortcut
            IWshRuntimeLibrary.IWshShortcut MyShortcut;
            string shortcutPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), string.Format("{0}.lnk", title));
            // Choose the path for the shortcut
            MyShortcut = (IWshRuntimeLibrary.IWshShortcut)WshShell.CreateShortcut(shortcutPath);
            // Where the shortcut should point to
            MyShortcut.TargetPath = rundllPath;

            MyShortcut.WorkingDirectory = Path.GetDirectoryName(rundllPath);

            // Description for the shortcut
            MyShortcut.Description = string.Format("Open {0}", title);

            // Location for the shortcut's icon
            MyShortcut.IconLocation = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//Styko Company//OpenLaunch//icons//" + iconname;

            // Create the shortcut at the given path
            MyShortcut.Save();
        }
    }
}